#include<iostream>
#include<websocketpp/server.hpp>
#include<websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> websocketsvr;
typedef websocketsvr::message_ptr message_ptr;

//websocket握手成功的回调
void WSOpen_Callback(websocketsvr* server,websocketpp::connection_hdl handler)
{
    std::cout<<"WebSocket握手成功"<<std::endl;
}

//websocket关闭连接的回调
void WSClose_Callback(websocketsvr* server,websocketpp::connection_hdl handler)
{
    std::cout<<"WebSocket关闭连接"<<std::endl;
}

//websocket收到消息的回调
void WSMsg_Callback(websocketsvr* server,websocketpp::connection_hdl handler,message_ptr msg)
{
    //通过handler获取连接
    websocketsvr::connection_ptr con=server->get_con_from_hdl(handler);
    std::cout<<"wsmsg:"<<msg->get_payload()<<std::endl;
    //组织响应
    std::string resp="Client say:"+msg->get_payload();
    //以文本方式发送
    con->send(resp,websocketpp::frame::opcode::text);
}

//收到http请求的回调
void Http_Callback(websocketsvr* server,websocketpp::connection_hdl handler)
{
    //通过handler获取连接
    websocketsvr::connection_ptr con=server->get_con_from_hdl(handler);
    std::cout<<"body:"<<con->get_request_body()<<std::endl;
    //获取http请求
    websocketpp::http::parser::request req=con->get_request();
    std::cout<<"method:"<<req.get_method()<<std::endl;
    std::cout<<"uri:"<<req.get_uri()<<std::endl;

    std::string body="<html><body><h1>Hello world</h1></body></html>";
    // con->set_body(body);
    // con->set_status(websocketpp::http::status_code::ok);
    con->set_body(con->get_request_body());
    con->append_header("Content-Type","text/html");
}

int main()
{
    //创建websocket服务器对象
    websocketsvr server;
    //设置日志等级
    server.set_access_channels(websocketpp::log::alevel::none);//默认不输出日志信息
    //初始化asio调度器
    server.init_asio();
    //启用地址重用
    server.set_reuse_addr(true);
    //设置回调函数
    server.set_open_handler(std::bind(WSOpen_Callback,&server,std::placeholders::_1));
    server.set_close_handler(std::bind(WSClose_Callback,&server,std::placeholders::_1));
    server.set_http_handler(std::bind(Http_Callback,&server,std::placeholders::_1));
    server.set_message_handler(std::bind(WSMsg_Callback,&server,std::placeholders::_1,std::placeholders::_2));
    //设置监听端口
    server.listen(8888);
    //获取连接
    server.start_accept();
    //启动服务
    server.run();
    return 0;
}